package m2_work;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.126.129");
        f.setUsername("admin");
        f.setPassword("admin");

        Channel channel = f.newConnection().createChannel();

        //定义队列
        channel.queueDeclare("task_queue",true,false,false,null);

        DeliverCallback deliverCallback = new DeliverCallback() {

            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                System.out.println("收到：" + msg);
                for (int i = 0; i < msg.length(); i++) {
                    if (msg.charAt(i) == '.') {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
                //手动发送 回值
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
                System.out.println("处理结束\n");
            }
        };

        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };
        //QOS 每次抓取的消息数量
        //每次抓取一条，这条消息没处理完之前，不会继续抓取下一条
        channel.basicQos(1);

        //消费数据
        System.out.println("开始消费数据");
        channel.basicConsume("task_queue",false, deliverCallback, cancelCallback);

    }
}

































































